package com.platform.server.service.impl;

import java.io.File;
import java.nio.file.Path;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.tools.ant.types.CommandlineJava.SysProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.easemob.server.example.api.IMUserAPI;
import com.easemob.server.example.comm.ClientContext;
import com.easemob.server.example.comm.EasemobRestAPIFactory;
import com.easemob.server.example.comm.body.IMUserBody;
import com.easemob.server.example.comm.wrapper.ResponseWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.platform.server.common.Constant;
import com.platform.server.dao.ServerDao;
import com.platform.server.dao.UserDao;
import com.platform.server.entity.EnterpriseInfo;
import com.platform.server.entity.Identity;
import com.platform.server.entity.User;
import com.platform.server.entity.Withdraw;
import com.platform.server.response.pojo.ReturnData;
import com.platform.server.service.UserService;
import com.platform.server.util.CfbpayDemoUtils;
import com.platform.server.util.RandomUtil;
import com.platform.server.util.RegexUtil;
import com.platform.server.util.StringTools;
import com.platform.server.util.WxpayDemoUtils;
import com.szrca.ima.utils.MD5Util;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	@Autowired
	private ServerDao serverDao; 
	


	EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES)
			.getAPIFactory();

	
	/**
	 * 人脸识别是否通过
	 */
	@Override
	public ReturnData updateFaceStatu(String statu, String id) {
		if (StringTools.isEmpty(statu)) {
			return new ReturnData(12, "参数有误");
		}
		userDao.updateFaceStatu(statu, id);
		userDao.updateIdentityStatu(statu, id);
		return new ReturnData(200, "成功");
	}

	/**
	 * 微信登录
	 */
	@Override
	public ReturnData selectWxnum(String openid) {
		User user = userDao.selectWxnum(openid);
		if (user != null) {
			return new ReturnData(user, 200, "成功");
		}
		return new ReturnData(100, "未找到相关信息");
	}

	/**
	 * 填写推荐人手机
	 */
	@Override
	public ReturnData insertRecommendMobile(String userid, String mobile) {
		if (StringTools.isEmpty(userid) || StringTools.isEmpty(mobile)) {
			return new ReturnData(12, "参数有误");
		}
		boolean str = mobile.matches("^(13|15|17|18)[0-9]{9}$");
		if (!str) {
			return new ReturnData(19, "手机号有误");
		}
		int count = userDao.selectUserRecommendMobile(userid);
		if (count > 0) {
			return new ReturnData(10, "你已经填写过了，不可重复填写");
		}
		Map<String, Object> map = userDao.selectUserIsRegister(mobile);
		if (map == null) {
			return new ReturnData(15, "无此账号信息，请重新输入");
		}
		if (!map.get("statu").equals("1")) {
			return new ReturnData(15, "无此账号信息，请重新输入");
		}
		int flag = userDao.insertRecommendMobile(userid, mobile);
		if (flag == 1) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 查看个人照片
	 */
	@Override
	public ReturnData selectUserPhoto(String userid) {
		if (StringTools.isEmpty(userid)) {
			return new ReturnData(12, "参数有误");
		}
		String photo = userDao.selectUserPhoto(userid);
		if (!StringTools.isEmpty(photo)) {
			String[] photos = photo.split(",");
			return new ReturnData(photos, 200, "成功");
		}
		return new ReturnData(100, "暂无数据");
	}

	/**
	 * 注册获取验证码
	 */
	@Override
	public ReturnData getRegisterCode(String mobile) {
		if (StringTools.isEmpty(mobile)) {
			return new ReturnData(27, "请填写正确手机号");
		}
		String code = RandomUtil.getRandomNumberString(4);
		Map<String, Object> map = userDao.selectUserIsRegister(mobile);
		if (map != null) {
			if ("1".equals(map.get("statu"))) {
				return new ReturnData(130, "该手机号已被注册");
			}
			int flag = userDao.updateRegisterCode(mobile, code);
			if (flag == 1) {
				return new ReturnData(code, 200, "成功");
			}
		}
		int flag = userDao.insertRegisterCode(mobile, code);
		if (flag == 1) {
			return new ReturnData(code, 200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 用户注册
	 */
	@Override
	public ReturnData UserRegister(String mobile, String code, String isEnter) {
		IMUserAPI user = (IMUserAPI) factory.newInstance(EasemobRestAPIFactory.USER_CLASS);
		if (StringTools.isEmpty(mobile)) {
			return new ReturnData(27, "请填写正确手机号");
		}
		if (StringTools.isEmpty(code)) {
			return new ReturnData(12, "参数有误");
		}
		Map<String, Object> map = userDao.selectUserIsRegister(mobile);
		if (map != null) {
			if (map.get("statu").equals("1")) {
				return new ReturnData(20, "该手机号已注册");
			}
			if (!map.get("code").equals(code)) {
				return new ReturnData(25, "验证码不正确");
			}
			if (!StringTools.isEmpty(isEnter) && isEnter.equals("1")) {
				EnterpriseInfo enterpriseInfo = new EnterpriseInfo();
				enterpriseInfo.setMobile(mobile);
				enterpriseInfo.setUser_id(map.get("id").toString());
				userDao.insertEnterpriseInfo(enterpriseInfo);
			}

			/*
			 * userDao.updateUserStatu(mobile,mobile); //注册成功后添加钱包
			 * userDao.insertUserWallet(map.get("id").toString()); //注册成功后添加用户积分
			 * userDao.insertUserIntegral(map.get("id").toString()); IMUserBody
			 * users = new IMUserBody(map.get("id").toString(),"123456","");
			 * ResponseWrapper responseBody =
			 * (ResponseWrapper)user.createNewIMUserSingle(users);
			 * if(responseBody != null && responseBody.getResponseStatus() ==
			 * 200) { }
			 */
			return new ReturnData(map, 200, "成功");
		}
		return new ReturnData(100, "请先注册");
	}

	/**
	 * 忘记密码获取验证码
	 */
	@Override
	public ReturnData getforgetPwdCode(String mobile) {
		if (StringTools.isEmpty(mobile)) {
			return new ReturnData(27, "请填写正确手机号");
		}
		String code = RandomUtil.getRandomNumberString(4);
		int flag = userDao.updateRegisterCode(mobile, code);
		if (flag == 1) {
			return new ReturnData(code, 200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 注册成功后设置密码
	 */
	@Override
	public ReturnData insertPassword(String id, String password, String surePassword) throws Exception {
		IMUserAPI user = (IMUserAPI) factory.newInstance(EasemobRestAPIFactory.USER_CLASS);
		if (StringTools.isEmpty(id) || StringTools.isEmpty(password) || StringTools.isEmpty(surePassword)) {
			return new ReturnData(12, "参数有误");
		}
		if (!password.equals(surePassword)) {
			return new ReturnData(20, "两次密码输入不一致");
		}
		if (password.length() < 5) {
			return new ReturnData(20, "密码长度不能少于6位");
		}
		password = MD5Util.getMD5(password);
		int flag = userDao.insertPassword(id, password);
		if (flag == 1) {
			Map<String, Object> map = userDao.selectUserIsRegister(id);
			userDao.updateUserStatu(map.get("mobile").toString(), map.get("mobile").toString());
			// 注册成功后添加钱包
			userDao.insertUserWallet(map.get("id").toString());
			// 注册成功后添加用户积分
			userDao.insertUserIntegral(id);
			IMUserBody users = new IMUserBody(id, "123456", "");
			ResponseWrapper responseBody = (ResponseWrapper) user.createNewIMUserSingle(users);
			user.disconnectIMUser("");
			if (responseBody != null && responseBody.getResponseStatus() == 200) {
			}
			return new ReturnData(map, 200, "注册成功");
		}
		return new ReturnData(100, "设置失败");
	}

	/**
	 * 忘记密码
	 */
	@Override
	public ReturnData forgetPassword(String mobile, String code, String password, String surePassword)
			throws Exception {
		if (StringTools.isEmpty(mobile)) {
			return new ReturnData(27, "请填写正确手机号");
		}
		if (!StringTools.isEmpty(code)) {
			Map<String, Object> map = userDao.selectUserIsRegister(mobile);
			if (map != null) {
				if (!map.get("code").equals(code)) {
					return new ReturnData(25, "验证码不正确");
				} else {
					return new ReturnData(200, "成功");
				}
			}
		}
		if (!StringTools.isEmpty(password) && !StringTools.isEmpty(surePassword)) {
			if (!password.equals(surePassword)) {
				return new ReturnData(20, "两次密码输入不一致");
			}
			int flag = userDao.forgetPassword(mobile, MD5Util.getMD5(password));
			if (flag == 1) {
				return new ReturnData(200, "修改成功");
			} else {
				return new ReturnData(100, "失败");
			}
		}
		return new ReturnData(100, "账号未注册");
	}

	/**
	 * 填写基本资料接口
	 */
	@Override
	public ReturnData setBaseInformation(User user) {
		if (user.getId() == null) {
			return new ReturnData(12, "参数有误");
		}
		// 查看该微信是否存在
		if (!StringTools.isEmpty(user.getWx_num())) {
			User userInfo = userDao.selectWxnum(user.getWx_num());
			if (userInfo != null) {
				return new ReturnData(140, "该微信号已被绑定");
			}
		}
		int flag = userDao.setBaseInformation(user);
		if (flag == 1) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 修改基本资料
	 */
	@Override
	public ReturnData updateBaseInformation(User user) {
		if (user.getId() == null) {
			return new ReturnData(12, "参数有误");
		}
		int flag = userDao.updateBaseInformation(user);
		if (flag == 1) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 登录获取验证码接口
	 */
	@Override
	public ReturnData getLoginCode(String mobile) {
		if (StringTools.isEmpty(mobile)) {
			return new ReturnData(27, "请填写正确手机号");
		}
		String code = RandomUtil.getRandomNumberString(4);
		int flag = userDao.updateRegisterCode(mobile, code);
		if (flag == 1) {
			return new ReturnData(code, 200, "成功");
		}
		return new ReturnData(100, "该账号还未注册，请先注册");
	}

	/**
	 * 验证码登录
	 */
	@Override
	public ReturnData codeLogin(String mobile, String code) {
		if (StringTools.isEmpty(mobile) || StringTools.isEmpty(code)) {
			return new ReturnData(12, "参数有误");
		}
		Map<String, Object> map = userDao.selectUserIsRegister(mobile);
		if (map != null) {
			if (!code.equals(map.get("code"))) {
				return new ReturnData(122, "验证码有误");
			}
			User user = userDao.mobileLogin(mobile);
			return new ReturnData(user, 200, "成功");
		}
		return new ReturnData(100, "该账号还未注册，请先注册");
	}

	/**
	 * 密码登录
	 */
	@Override
	public ReturnData passwordLogin(String mobile, String password) throws Exception {
		if (StringTools.isEmpty(mobile) || StringTools.isEmpty(password)) {
			return new ReturnData(12, "参数有误");
		}
		Map<String, Object> map = userDao.selectUserIsRegister(mobile);
		if (map != null) {
			if ("0".equals(map.get("is_ban"))) {
				return new ReturnData(20, "您的账号已被禁用");
			}
			if(map.get("username")==null||StringTools.isEmpty(map.get("username").toString())){
				return new ReturnData(100, "账号未注册");
			}
		}
		password = MD5Util.getMD5(password);
		User user = userDao.passwordLogin(mobile, password);
		if (user != null) {
			// 登录成功后修改登录时间
			userDao.updateLoginTime(mobile);
			return new ReturnData(user, 200, "登录成功");
		}
		return new ReturnData(100, "账号或密码错误，请重新输入");
	}

	/**
	 * 个人信息接口
	 */
	@Override
	public ReturnData selectUserInfo(String id) {
		// 基本信息
		Map<String, Object> map = userDao.selectUserIsRegister(id);
		if (map == null) {
			return new ReturnData(100, "未找到该用户信息");
		}
		Map<String, Object> hashMap = new HashMap<>();
		hashMap.put("integral_rank", map.get("integral_rank"));
		hashMap.put("isvip", map.get("isvip"));

		String selectis_vip = userDao.selectis_vip(id, "1");
		String selectis_vip2 = userDao.selectis_vip(id, "3");
		if (!StringTools.isEmpty(selectis_vip) && selectis_vip.equals("1")) {
			hashMap.put("vipLevel", "vip1");
		} else if (!StringTools.isEmpty(selectis_vip2) && selectis_vip2.equals("1")) {
			hashMap.put("vipLevel", "vip2");
		}
		if (!StringTools.isEmpty((String) map.get("username"))) {
			hashMap.put("baseInfo", "已完善");
		} else {
			hashMap.put("baseInfo", "未完善");
		}
		if (!StringTools.isEmpty((String) map.get("mobile"))) {
			hashMap.put("mobile", map.get("mobile"));
			// 推荐人手机号
			String selectUserParentMobile = userDao.selectUserParentMobile(map.get("mobile").toString());
			if (!StringTools.isEmpty(selectUserParentMobile)) {
				hashMap.put("recommendMobile", selectUserParentMobile);
			} else {
				hashMap.put("recommendMobile", "");
			}
		} else {
			hashMap.put("mobile", "");
		}
		// 身份认证
		int flag1 = userDao.selectUserIdentity(id);
		if (flag1 > 0) {
			hashMap.put("identity", "已认证");
		} else {
			hashMap.put("identity", "未认证");
		}
		// 企业认证
		// int flag2 = userDao.selectUserAuthentication(id);
		String flag2 = userDao.selectUserAuthenticationAudit(id);
		if (!StringTools.isEmpty(flag2) && flag2.equals("1")) {
			hashMap.put("authentication", "已认证");
		} else if (!StringTools.isEmpty(flag2) && flag2.equals("0")) {
			hashMap.put("authentication", "待审核");
		} else {
			hashMap.put("authentication", "未认证");
		}
		// 职业资格证
		int flag3 = userDao.selectUserQualification(id);
		if (flag3 > 0) {
			hashMap.put("qualification", "已完善");
		} else {
			hashMap.put("qualification", "未完善");
		}
		// 个人照片
		if (!StringTools.isEmpty((String) map.get("personal_photo"))) {
			hashMap.put("personal_photo", "已上传");
		} else {
			hashMap.put("personal_photo", "未上传");
		}
		// 推荐人手机号
		/*
		 * int flag4 = userDao.selectUserRecommendMobile(id); if (flag4 > 0) {
		 * hashMap.put("recommend_mobile", "已填写"); } else {
		 * hashMap.put("recommend_mobile", "未填写"); }
		 */
		// 查看是否是员工
		String selectStaff = userDao.selectStaff(id);
		if (selectStaff != null && selectStaff.equals("1")) {
			hashMap.put("is_staff", "是");
		} else {
			hashMap.put("is_staff", "否");
		}
		Map<String, Object> selectenterName = userDao.selectenterName(id);
		if (selectenterName != null && selectenterName.size() > 0) {
			hashMap.put("companyName", selectenterName.get("company_name").toString());
			hashMap.put("enterId", selectenterName.get("id").toString());
		}
		String selectenterEnter = userDao.selectenterEnter(id);
		if (!StringTools.isEmpty(selectenterEnter)) {
			hashMap.put("isEnter", 1);
			hashMap.put("identity", "已认证");
		} else {
			hashMap.put("isEnter", 0);
		}
		String selectUser = userDao.isSelectUser(id);
		if (!StringTools.isEmpty(selectUser)) {
			hashMap.put("isUser", 1);
		} else {
			hashMap.put("isUser", 0);
		}
		// 查看用户的关注人
		String[] follower = userDao.selectmyInterestList(id);
		// 查看用户的粉丝
		String[] fans = userDao.selectMyFans(id);
		hashMap.put("follower", follower.length);
		hashMap.put("fans", fans.length);
		String qrCode = qrCode(id);
		hashMap.put("qrCode", qrCode);
		return new ReturnData(hashMap, 200, "成功");
	}

	public String qrCode(String user_id) {

		File file2 = new File(UserServiceImpl.class.getResource("/").getFile());
		File parentFile = file2.getParentFile().getParentFile().getParentFile();
		System.out.println(parentFile);
		String path = parentFile.toString() + "//htxFile//images//" + user_id + ".png";
		System.out.println(path);
		File file3 = new File(path);
		if (!file3.exists()) {
			int width = 268;
			int height = 268;
			String format = "png";
			String text = "http://hanya.htx328.com/htx-backer/share?userId=" + user_id;
			Hashtable hints = new Hashtable();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
			hints.put(EncodeHintType.MARGIN, 2);
			try {
				BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
				Path file = new java.io.File(path).toPath();
				MatrixToImageWriter.writeToPath(bitMatrix, format, file);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return "http://" + Constant.SERVER_NAME + ":8080//" + "htxFile//images//" + user_id + ".png";
	}

	/**
	 * 绑定信息
	 */
	@Override
	public ReturnData selectUserBindingInfo(String id) {
		Map<String, Object> map = userDao.selectUserIsRegister(id);
		Map<String, Object> hashMap = new HashMap<>();
		if (map == null) {
			return new ReturnData(100, "未找到该用户信息");
		}
		hashMap.put("wx_num", map.get("wx_num"));
		hashMap.put("wx_name", map.get("wx_name"));
		hashMap.put("mobile", map.get("mobile"));
		// 是否完善支付宝
		int flag1 = userDao.selectzfbInfo(id);
		if (flag1 > 0) {
			hashMap.put("binding_zfb", "已完善");
		} else {
			hashMap.put("binding_zfb", "未完善");
		}
		// 是否完善银行卡
		int flag2 = userDao.selectBankInfo(id);
		if (flag2 > 0) {
			hashMap.put("binding_bank", "已完善");
		} else {
			hashMap.put("binding_bank", "未完善");
		}
		return new ReturnData(hashMap, 200, "成功");
	}

	/**
	 * 职业资格认证
	 */
	@Override
	public ReturnData insertJobCertification(String job, String skill, String certification_photo, String id) {
		if (StringTools.isEmpty(job) || StringTools.isEmpty(skill) || StringTools.isEmpty(certification_photo)
				|| StringTools.isEmpty(id)) {
			return new ReturnData(12, "参数有误");
		}
		Map<String, Object> map = userDao.selectJobCertification(id);
		if (map != null) {
			return new ReturnData(100, "您已申请过认证，请勿重复认证");
		}
		int flag = userDao.insertJobCertification(job, skill, certification_photo, id);
		if (flag == 1) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 我的关注列表
	 */
	@Override
	public ReturnData selectmyInterestList(String id, Integer pageSize, Integer pageNo) {
		if (StringTools.isEmpty(id)) {
			return new ReturnData(12, "参数有误");
		}
		List<Map<String, Object>> lists = new ArrayList<>();
		PageHelper.startPage(pageNo, pageSize);
		String[] strs = userDao.selectmyInterestList(id);
		for (int i = 0; i < strs.length; i++) {
			Map<String, Object> map = userDao.selectUserIsRegister(strs[i]);
			// 查看用户身份证是否已经认证
			int flag = userDao.selectUserIdentity(strs[i]);
			if (flag > 0) {
				map.put("identity", "已认证");
			} else {
				map.put("identity", "未认证");
			}
			// 查看用户平均星级
			Map<String, Object> hashMap = userDao.selectAvgLevel(strs[i]);
			Double avg = 0D;
			if (hashMap != null && (Long) hashMap.get("总条目数") != 0) {
				Double sum = (Double) hashMap.get("总星级数");
				Long count = (Long) hashMap.get("总条目数");
				avg = sum / count.doubleValue();
			}
			map.put("avg", avg);
			lists.add(map);
		}
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(lists);
		return new ReturnData(lists, pageInfo.getPages(), pageInfo.getTotal(), 200, "成功");
	}

	/**
	 * 我的粉丝列表
	 */
	@Override
	public ReturnData selectMyFans(String id, Integer pageSize, Integer pageNo) {
		if (StringTools.isEmpty(id)) {
			return new ReturnData(12, "参数有误");
		}
		List<Map<String, Object>> lists = new ArrayList<>();
		PageHelper.startPage(pageNo, pageSize);
		String[] strs = userDao.selectMyFans(id);
		for (int i = 0; i < strs.length; i++) {
			Map<String, Object> map = userDao.selectUserIsRegister(strs[i]);
			// 查看用户身份证是否已经认证
			int flag = userDao.selectUserIdentity(strs[i]);
			if (flag > 0) {
				map.put("identity", "已认证");
			} else {
				map.put("identity", "未认证");
			}
			// 查看用户平均星级
			Map<String, Object> hashMap = userDao.selectAvgLevel(strs[i]);
			Double avg = 0D;
			if (hashMap != null && (Long) hashMap.get("总条目数") != 0) {
				Double sum = (Double) hashMap.get("总星级数");
				Long count = (Long) hashMap.get("总条目数");
				avg = sum / count.doubleValue();
			}
			map.put("avg", avg);
			// 查看我的粉丝列表是否有我关注的人
			int count = userDao.selectMyFansIsattention(id, strs[i]);
			if (count > 0) {
				map.put("attention", 1);
			} else {
				map.put("attention", 0);
			}
			lists.add(map);
		}
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(lists);
		return new ReturnData(lists, pageInfo.getPages(), pageInfo.getTotal(), 200, "成功");
	}

	/**
	 * 实名认证信息
	 */
	@Override
	public ReturnData selectAuthentication(Integer id) {
		if (id == null) {
			return new ReturnData(12, "参数有误");
		}
		Map<String, Object> map = userDao.selectAuthentication(id);
		if (map != null) {
			String face_statu = (String) map.get("face_statu");
			if (StringTools.isEmpty(face_statu)) {
				map.put("face_statu", 2);
			}
			String username = (String) map.get("username");
			if (StringTools.isEmpty(username)) {
				map.put("base_info", "未完善");
			} else {
				map.put("base_info", "已完善");
			}
			String identity_audit = (String) map.get("identity_audit");
			if (StringTools.isEmpty(identity_audit)) {
				map.put("identity_audit", 3);
			}
			String enterprise_audit = (String) map.get("enterprise_audit");
			if (StringTools.isEmpty(enterprise_audit)) {
				map.put("enterprise_audit", 3);
			}
			String identity_card = (String) map.get("identity_card");
			if (StringTools.isEmpty(identity_card)) {
				map.put("identity_card", null);
			}
			return new ReturnData(map, 200, "成功");
		}
		return new ReturnData(100, "未找到相关信息");
	}

	/**
	 * 企业认证
	 */
	@Override
	public ReturnData insertEnterpriseInfo(EnterpriseInfo e) {
		if (StringTools.isEmpty(e.getCompany_name()) || StringTools.isEmpty(e.getCompany_person())
				|| StringTools.isEmpty(e.getCompany_address()) || StringTools.isEmpty(e.getFixation_mobile())
				|| StringTools.isEmpty(e.getMobile()) || StringTools.isEmpty(e.getBusiness_license())
				|| StringTools.isEmpty(e.getUser_id()) || StringTools.isEmpty(e.getCard_just())
				|| StringTools.isEmpty(e.getCard_back())) {
			return new ReturnData(12, "参数有误");
		}
		if (!RegexUtil.isMobile(e.getMobile())) {
			return new ReturnData(27, "请填写正确手机号");
		}
		Map<String, Object> selectCompany = userDao.selectCompany(e.getUser_id());
		int flag = 0;
		if (selectCompany != null) {
			flag = userDao.updateEnterpriseInfo(e);
		} else {
			flag = userDao.insertEnterpriseInfo(e);
		}

		if (flag == 1) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 上传个人照片
	 */
	@Override
	public ReturnData updateUserPhoto(String userid, String photo) {
		if (StringTools.isEmpty(photo) || StringTools.isEmpty(userid)) {
			return new ReturnData(12, "参数有误");
		}
		int flag = userDao.updateUserPhoto(userid, photo);
		if (flag == 1) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 上传个人视频
	 */
	@Override
	public ReturnData insertVideo(String userid, String videoLink, String videoTime, String videoImage) {
		if (StringTools.isEmpty(userid) || StringTools.isEmpty(videoLink) || StringTools.isEmpty(videoTime)) {
			return new ReturnData(12, "参数有误");
		}
		int flag = userDao.insertVideo(userid, videoLink, videoTime, videoImage);
		if (flag == 1) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 关注用户
	 */
	@Override
	public ReturnData attentionUser(String userid1, String userid2) {
		if (StringTools.isEmpty(userid1) || StringTools.isEmpty(userid2)) {
			return new ReturnData(12, "参数有误");
		}
		// 查看是否是我关注的人
		int count = userDao.selectMyFansIsattention(userid1, userid2);
		if (count > 0) {
			return new ReturnData(120, "已关注");
		}
		int flag = userDao.attentionUser(userid1, userid2);
		if (flag == 1) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 提现申请
	 */
	@Override
	public ReturnData insertWithdrawApply(Withdraw w) {
		ReturnData returnData = new ReturnData("");
		if (StringTools.isEmpty(w.getBank_card()) || StringTools.isEmpty(w.getReal_name())
				|| StringTools.isEmpty(w.getMoney()) || StringTools.isEmpty(w.getUser_id())
				|| StringTools.isEmpty(w.getType())) {
			return new ReturnData(12, "参数有误");
		}
	/*	if ("2".equals(w.getType())) {
			if (!RegexUtil.isMobile(w.getBank_card())) {
				return new ReturnData(27, "支付宝账号有误");
			}
		}*/
		// 提现之前查看用户是否有金额
		String userMoney = userDao.selectUserMoney(w.getUser_id());
		if (Double.parseDouble(userMoney) < Double.parseDouble(w.getMoney()) || "0.00".equals(userMoney)) {
			return new ReturnData(20, "提现金额有误");
		}
		if (2D > Double.parseDouble(w.getMoney())) {
			return new ReturnData(22, "提现金额必须大于二元");
		}
		// 查看用户当月是否有提现记录
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String str = sdf.format(new Date());
		/*int num = userDao.selectWithdrawNum(str, w.getUser_id());
		if (num > 0) {
			return new ReturnData(120, "每月只能提现一次");
		}*/

		String randomString = WxpayDemoUtils.getRandomString(16);

		// 查看开关
		Integer on_off = userDao.withdrawOnOff();
		w.setState("待审核");
		w.setWithdrawal_order(randomString);
		ReturnData transfer  = null;
		// 1 = 开
		// 提现金额
		Double money = Double.valueOf(w.getMoney());
		// 手续费
		Double service_fee = money*0.008;
		// 实际到账金额
		Double actualMoney = money-service_fee;
		
		// 手续费不大于 1元 扣除一元
		if(service_fee<1){
			actualMoney = money-1;
		}
		if (on_off == 1) {
			if (w.getType().equals("2")) {
				 transfer = CfbpayDemoUtils.transfer(actualMoney, w.getBank_card(),w.getReal_name(), null,2);
			}
			if (w.getType().equals("1")) {
				 transfer = CfbpayDemoUtils.transfer(actualMoney, w.getBank_card(),w.getReal_name(), w.getOpen_bank_code(),1);
			}	
			if (transfer.getCode() == 200) {
				// 修改用户的余额
				Map<String, Object> map = new HashMap();
				w.setOrder_id(transfer.getData()+"");
				userDao.insertWithdrawApply(w);
				String s = userDao.selectUserMoney("1");
				serverDao.insertCancelOrder(w.getUser_id(), w.getMoney(), "提现",randomString,userMoney, Constant.EXPEND,s, null);
				// 发起提现后添加消息表记录
				int flag2 = userDao.insertMessageRecord(w.getUser_id(), w.getId().toString());
				if (flag2 > 0) {
					return new ReturnData(200, "成功");
				}
			} else {
				new ReturnData(100, transfer.getMsg());
			}
		} else {
			userDao.insertWithdrawApply(w);
			String s = userDao.selectUserMoney("1");
			serverDao.insertCancelOrder(w.getUser_id(), w.getMoney(), "提现", randomString,userMoney, Constant.EXPEND,s, null);
			// 发起提现后添加消息表记录
			int flag2 = userDao.insertMessageRecord(w.getUser_id(), w.getId().toString());
			if (flag2 > 0) {
				return new ReturnData(200, "成功");
			}
		}
		return new ReturnData(100, "失败");
	}


	/**
	 * 钱包明细
	 */
	@Override
	public ReturnData selectWalletInfo(String userid) {
		if (StringTools.isEmpty(userid)) {
			return new ReturnData(12, "参数有误");
		}
		// 查看服务已完成收益
		List<Map<String, Object>> list1 = userDao.selectServerMoney(userid);
		for (int i = 0; i < list1.size(); i++) {
			list1.get(i).put("type", "已完成服务");
		}
		// 查看提现记录
		List<Map<String, Object>> list2 = userDao.selectCancelOrder(userid, "提现");
		for (int i = 0; i < list2.size(); i++) {
			list2.get(i).put("type", "提现");
		}
		// 查看充值记录
		List<Map<String, Object>> rechargeRecord = userDao.selectRechargeRecord(userid);
		for (int i = 0; i < rechargeRecord.size(); i++) {
			rechargeRecord.get(i).put("type", "充值");
		}
		// 查看已取消支出订单 // 违约金
		List<Map<String, Object>> cancelOrder = userDao.selectCancelOrders(userid);
		for (int i = 0; i < cancelOrder.size(); i++) {
			cancelOrder.get(i).put("type", cancelOrder.get(i).get("type").toString());
		}

		// 查看已取消收入订单 // 违约金
		List<Map<String, Object>> income = userDao.selectCancelOrdersIncome(userid);
		for (int i = 0; i < income.size(); i++) {
			income.get(i).put("type", income.get(i).get("type").toString());
		}

		// 查看已取消收入订单
		List<Map<String, Object>> cancelOrderRevenue = userDao.selectCancelOrder(userid, "预付返还");
		for (int i = 0; i < cancelOrderRevenue.size(); i++) {
			cancelOrderRevenue.get(i).put("type", "预付返还");
		}
		// 查看付款订单
		List<Map<String, Object>> paymentOrder = userDao.selectCancelOrder(userid, "预约预付");
		for (int i = 0; i < paymentOrder.size(); i++) {
			paymentOrder.get(i).put("type", "付款");
		}
		// 查看vip订单
		List<Map<String, Object>> vip = userDao.selectCancelOrder(userid, "会员");
		for (int i = 0; i < vip.size(); i++) {
			vip.get(i).put("type", "购买会员");
		}
		// 查看提现失败订单
		List<Map<String, Object>> withdraw = userDao.selectCancelOrder(userid, "提现失败");
		for (int i = 0; i < withdraw.size(); i++) {
			withdraw.get(i).put("type", "提现失败");
		}

		// 查看我的打赏记录
		List<Map<String, Object>> my_reward = userDao.selectCancelOrder(userid, "打赏");
		for (int i = 0; i < my_reward.size(); i++) {
			my_reward.get(i).put("type", "打赏");
		}
		// 查看打赏别人的记录
		List<Map<String, Object>> other_reward = userDao.selectCancelOrder(userid, "打赏对方");
		for (int i = 0; i < other_reward.size(); i++) {
			other_reward.get(i).put("type", "打赏对方");
		}

		// 查看打赏别人的记录
		List<Map<String, Object>> demand_finish = userDao.selectCancelOrder(userid, "需求完成");
		for (int i = 0; i < demand_finish.size(); i++) {
			demand_finish.get(i).put("type", "需求完成");
		}
		// 查看提成
		List<Map<String, Object>> tc = userDao.selectCancelOrder(userid, "提成");
		for (int i = 0; i < tc.size(); i++) {
			tc.get(i).put("type", "提成");
		}
		List<Map<String, Object>> tc2 = userDao.selectCancelOrder(userid, "交易提成");
		for (int i = 0; i < tc2.size(); i++) {
			tc2.get(i).put("type", "交易提成");
		}
		List<Map<String, Object>> tc3 = userDao.selectCancelOrder(userid, "会员提成");
		for (int i = 0; i < tc3.size(); i++) {
			tc3.get(i).put("type", "会员提成");
		}
		list1.addAll(my_reward);
		list1.addAll(other_reward);
		list1.addAll(list2);
		list1.addAll(rechargeRecord);
		list1.addAll(cancelOrder);
		list1.addAll(cancelOrderRevenue);
		list1.addAll(paymentOrder);
		list1.addAll(vip);
		list1.addAll(withdraw);
		list1.addAll(demand_finish);
		list1.addAll(income);
		list1.addAll(tc);
		list1.addAll(tc2);
		list1.addAll(tc3);
		if (list1.size() == 0) {
			return new ReturnData(100, "暂无数据");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Collections.sort(list1, new Comparator<Map<String, Object>>() {
			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
				return (sdf.format((Date) o2.get("create_time"))).compareTo(sdf.format((Date) o1.get("create_time")));
			}
		});
		// 查看列表中的时间段有几个
		String[] d = new String[list1.size()];
		;
		for (int i = 0; i < list1.size(); i++) {
			Date date = (Date) list1.get(i).get("create_time");
			String str = sdf.format(date);
			String time = str.substring(0, str.lastIndexOf("-"));
			d[i] = time;
		}
		List<String> list = Arrays.asList(d);
		Set<String> set = new HashSet<String>(list);
		String[] datetime = (String[]) set.toArray(new String[0]);
		// 按月份显示
		List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < datetime.length; i++) {
			Double sum = 0.0;
			Map<String, Object> hashMap = new HashMap<String, Object>();
			List<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
			String date = datetime[i];
			for (int j = 0; j < list1.size(); j++) {
				int index2 = sdf.format(list1.get(j).get("create_time")).lastIndexOf("-");
				String date2 = sdf.format(list1.get(j).get("create_time")).substring(0, index2);
				if (date.equals(date2)) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("time", list1.get(j).get("create_time"));
					map.put("money", list1.get(j).get("money"));
					map.put("type", list1.get(j).get("type"));
					map.put("orderId", list1.get(j).get("order_id"));
					if (list1.get(j).get("type").equals("购买会员") ||list1.get(j).get("type").equals("提现") || list1.get(j).get("type").equals("付款")
							|| list1.get(j).get("type").equals("打赏对方") || list1.get(j).get("type").equals("需求完成")
							|| list1.get(j).get("type").equals("需方违约支出")
							|| list1.get(j).get("type").equals("服务违约支出")) {
						sum += -Double.parseDouble(list1.get(j).get("money").toString());
					} else {
							sum += Double.parseDouble(list1.get(j).get("money").toString());
					}
					arrayList.add(map);
				}
				hashMap.put("lists", arrayList);
			}
			hashMap.put("sum", sum);
			hashMap.put("date", date);
			lists.add(hashMap);
		}
		if (lists.size() > 0) {
			Collections.sort(lists, new Comparator<Map<String, Object>>() {
				public int compare(Map<String, Object> o1, Map<String, Object> o2) {
					return ((String) o2.get("date")).compareTo((String) o1.get("date"));
				}
			});
			return new ReturnData(lists, 200, "成功");
		}
		return new ReturnData(100, "暂无信息");
	}

	/**
	 * 取消关注用户
	 */
	@Override
	public ReturnData unfriendedUser(String userid1, String userid2) {
		if (StringTools.isEmpty(userid1) || StringTools.isEmpty(userid2)) {
			return new ReturnData(12, "参数有误");
		}
		int flag = userDao.unfriendedUser(userid1, userid2);
		if (flag > 0) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 查看我的推荐人列表
	 */
	@Override
	public ReturnData selectMyReferrerList(String mobile) {
		if (StringTools.isEmpty(mobile)) {
			return new ReturnData(12, "参数有误");
		}
		List<Map<String, Object>> lists = userDao.selectMyReferrerList(mobile);
		if (lists.size() > 0) {
			return new ReturnData(lists, 200, "成功");
		}
		return new ReturnData(100, "暂无数据");
	}

	/**
	 * 查看我的积分
	 */
	@Override
	public ReturnData selectMyIntegral(String userid) {
		if (StringTools.isEmpty(userid)) {
			return new ReturnData(12, "参数有误");
		}
		// 查看积分使用方式
		Map<String, Object> hashMap = userDao.selectIntegeralWay();
		Map<String, Object> map = userDao.selectMyIntegral(userid);
		Integer integral = Integer.parseInt(map.get("integral").toString());
		hashMap.put("integral", integral);
		if (integral > 100000) {
			hashMap.put("integral_rank", "金牌会员");
			hashMap.put("content", "已是最高等级，请继续保持");
			hashMap.put("sum", "已是最高等级，请继续保持");
		} else if (integral > 10000) {
			hashMap.put("integral_rank", "银牌会员");
			Integer num = 100000 - integral;
			hashMap.put("content", "再获取" + num + "积分升级为金牌会员");
			hashMap.put("sum", "100000");
		} else if (integral > 1000) {
			hashMap.put("integral_rank", "铜牌会员");
			Integer num = 10000 - integral;
			hashMap.put("content", "再获取" + num + "积分升级为银牌会员");
			hashMap.put("sum", "10000");
		} else {
			hashMap.put("integral_rank", "普通会员");
			Integer num = 1000 - integral;
			hashMap.put("content", "再获取" + num + "积分升级为铜牌会员");
			hashMap.put("sum", "1000");
		}
		int flag = userDao.updateIntegralGrade(userid, hashMap.get("integral_rank").toString());
		return new ReturnData(hashMap, 200, "成功");
	}

	/**
	 * 查看我的积分记录
	 */
	@Override
	public ReturnData selectIntegralRecord(String userid, Integer pageSize, Integer pageNo) {
		if (StringTools.isEmpty(userid)) {
			return new ReturnData(12, "参数有误");
		}
		PageHelper.startPage(pageNo, pageSize);
		List<Map<String, Object>> lists = userDao.selectIntegralRecord(userid);
		if (lists.size() == 0) {
			return new ReturnData(100, "暂无数据");
		}
		for (int i = 0; i < lists.size(); i++) {
			String recommend_id = (String) lists.get(i).get("recommend_id");
			if (!StringTools.isEmpty(recommend_id)) {
				Map<String, Object> map = userDao.selectUserIsRegister(recommend_id);
				lists.get(i).put("title", map.get("username") + "下单完成，获得推荐奖励");
			}
		}
		PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(lists);
		return new ReturnData(lists, pageInfo.getPages(), pageInfo.getTotal(), 200, "成功");
	}

	/**
	 * 我的账户
	 */
	@Override
	public ReturnData selectUserAccount(String userid) {
		if (StringTools.isEmpty(userid)) {
			return new ReturnData(12, "参数有误");
		}
		Map<String, Object> map = new HashMap<>();
		// 查看用户余额
		String money = userDao.selectUserMoney(userid);
		map.put("money", money);
		// 查看用户积分
		Map<String, Object> hm = userDao.selectMyIntegral(userid);
		map.put("integral", hm.get("integral"));
		map.put("user_id", hm.get("user_id"));
		// 查看用户优惠券
		int count = userDao.selectUserDiscountNum(userid);
		map.put("discount", count);
		String selectProfitTotal = userDao.selectProfitTotal(userid);
		String selectVipProfitTotal = userDao.selectVipProfitTotal(userid);
		String selectEntProfitTotal = userDao.selectEntProfitTotal(userid);
		Double profit = 0D;
		if (!StringTools.isEmpty(selectProfitTotal) && !StringTools.isEmpty(selectVipProfitTotal)) {
			profit = Double.parseDouble(selectProfitTotal) + Double.parseDouble(selectVipProfitTotal);
		}
		if (!StringTools.isEmpty(selectProfitTotal) && StringTools.isEmpty(selectVipProfitTotal)) {
			profit = Double.parseDouble(selectProfitTotal);
		}
		if (StringTools.isEmpty(selectProfitTotal) && !StringTools.isEmpty(selectVipProfitTotal)) {
			profit = Double.parseDouble(selectVipProfitTotal);
		}
		DecimalFormat df = new DecimalFormat("#.00");
		String pro = null;
		if (profit != null) {
			pro = df.format(profit);
		}
		map.put("profitTotal", pro);
		map.put("entProfitTotal", selectEntProfitTotal);
		return new ReturnData(map, 200, "成功");
	}

	/**
	 * 身份认证
	 */
	@Override
	public ReturnData insertIdentityAuthentication(Identity i) {
		if (StringTools.isEmpty(i.getUserid()) || StringTools.isEmpty(i.getUsername())
				|| StringTools.isEmpty(i.getIdentity_card()) || StringTools.isEmpty(i.getIdentity_front())
				|| StringTools.isEmpty(i.getIdentity_side())) {
			return new ReturnData(12, "参数有误");
		}
		if (!RegexUtil.isIdCardNo(i.getIdentity_card())) {
			return new ReturnData(19, "身份证号码有误");
		}
		// 查看该用户是否已经认证过
		Map<String, Object> map = userDao.selectCountIdentityAuthentication(i);
		if (map != null) {
			if (map.get("audit").equals("1")) {
				return new ReturnData(100, "请勿重复认证");
			}
			/*
			 * if(!map.get("identity_card").equals(i.getIdentity_card())){
			 * return new ReturnData(120,"一个手机号只能绑定一个身份信息"); }
			 */
			userDao.updateIdentityAuthentication(i);
			return new ReturnData(200, "成功");
		}
		/*
		 * //查看该身份证号码是否有人使用 int count = userDao.countAuthenticationNum(i);
		 * if(count > 0){ return new ReturnData(130,"该身份证号已经使用"); }
		 */
		int flag = userDao.insertIdentityAuthentication(i);
		if (flag > 0) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 删除个人照片接口
	 */
	@Override
	public ReturnData deleteUserPhoto(String userid, String photo) {
		if (StringTools.isEmpty(userid) || StringTools.isEmpty(photo)) {
			return new ReturnData(12, "参数有误");
		}
		// 查看用户个人照片
		String userPhoto = userDao.selectUserPhoto(userid);
		int flag = userDao.deleteUserPhoto(userid, userPhoto.replace(photo, ""));
		if (flag > 0) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 查看职业资格证
	 */
	@Override
	public ReturnData selectJobCertification(String userid) {
		if (StringTools.isEmpty(userid)) {
			return new ReturnData(12, "参数有误");
		}
		Map<String, Object> map = userDao.selectJobCertification(userid);
		if (map != null) {
			return new ReturnData(map, 200, "成功");
		}
		return new ReturnData(100, "未找到该信息");
	}

	/**
	 * 修改登录密码
	 */
	@Override
	public ReturnData updateLoginPassword(String oldPassword, String newPassword, String surePassword, String userid)
			throws Exception {
		if (StringTools.isEmpty(oldPassword) || StringTools.isEmpty(newPassword) || StringTools.isEmpty(surePassword)
				|| StringTools.isEmpty(userid)) {
			return new ReturnData(12, "参数有误");
		}
		if (!newPassword.equals(surePassword)) {
			return new ReturnData(19, "两次密码输入不一致");
		}
		if (newPassword.length() < 5) {
			return new ReturnData(20, "密码长度不能少于6位");
		}
		Map<String, Object> map = userDao.selectUserIsRegister(userid);
		if (map == null) {
			return new ReturnData(20, "未找到该用户信息");
		}
		String password = map.get("pass_word").toString();
		if (!password.equals(MD5Util.getMD5(oldPassword))) {
			return new ReturnData(30, "原密码输入不正确");
		}
		int flag = userDao.updateLoginPassword(MD5Util.getMD5(newPassword), userid);
		if (flag > 0) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 修改支付密码获取验证码
	 */
	@Override
	public ReturnData updatePayPasswordGetCode(String mobile) {
		if (StringTools.isEmpty(mobile)) {
			return new ReturnData(12, "参数有误");
		}
		if (StringTools.isEmpty(mobile)) {
			return new ReturnData(27, "请填写正确手机号");
		}
		Map<String, Object> map = userDao.selectUserIsRegister(mobile);
		if (map == null) {
			return new ReturnData(20, "请先注册");
		}
		if (map.get("statu").equals("0")) {
			return new ReturnData(20, "请先注册");
		}
		String code = RandomUtil.getRandomNumberString(4);
		int flag = userDao.updatePayPasswordGetCode(mobile, code);
		if (flag > 0) {
			return new ReturnData(code, 200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 意见反馈
	 */
	@Override
	public ReturnData insertFeedback(String userid, String content) {
		if (StringTools.isEmpty(userid) || StringTools.isEmpty(content)) {
			return new ReturnData(12, "参数有误");
		}
		int flag = userDao.insertFeedback(userid, content);
		if (flag > 0) {
			return new ReturnData(200, "成功");
		}
		return new ReturnData(100, "失败");
	}

	/**
	 * 获取个人基本资料
	 */
	@Override
	public ReturnData selectUserinfo(Integer userid) {
		if (userid == null) {
			return new ReturnData(12, "参数有误");
		}
		User user = userDao.selectUserinfo(userid);
		if (user != null) {
			return new ReturnData(user, 200, "成功");
		}
		return new ReturnData(100, "未找到相关信息");
	}

	/**
	 * 查看推荐人手机号
	 */
	@Override
	public ReturnData selectRecommendMobile(String userid) {
		String mobile = userDao.selectRecommendMobile(userid);
		if (StringTools.isEmpty(mobile)) {
			return new ReturnData(100, "暂无数据");
		} else {
			return new ReturnData(mobile, 200, "成功");
		}
	}

	/**
	 * 查看企业认证
	 */
	@Override
	public ReturnData selectCompany(String userid) {
		Map<String, Object> map = userDao.selectCompany(userid);
		if (map != null) {
			return new ReturnData(map, 200, "成功");
		}
		return new ReturnData(100, "暂无数据");
	}

	/**
	 * 添加下级
	 */
	@Override
	public ReturnData addUserGrade(User user) {
		if (StringTools.isEmpty(user.getUser_id())) {
			return new ReturnData(12, "参数有误");
		}
		String selectUsertEnter = userDao.selectUsertEnter(user.getUser_id());
		if (!StringTools.isEmpty(selectUsertEnter)) {
			return new ReturnData(12, "企业员工无法推荐");
		}
		Map<String, Object> selectUserMobile = userDao.selectUserMobile(user.getUser_id());
		if (selectUserMobile == null) {
			return new ReturnData(12, "没有该用户");
		}
		String selectRecommendMobileUserId = userDao
				.selectRecommendMobileUserId(selectUserMobile.get("mobile").toString());
		if (StringTools.isEmpty(selectRecommendMobileUserId)) {
			return new ReturnData(12, "没有推荐人");
		}
		user.setParent_id(selectRecommendMobileUserId);
		String selectUsertEnter2 = userDao.selectUsertEnter(selectRecommendMobileUserId);
		if (!StringTools.isEmpty(selectUsertEnter2)) {
			return new ReturnData(12, "企业员工无法推荐");
		}
		Map<String, Object> selectCompany = userDao.selectCompany(user.getParent_id());
		if (selectCompany != null && selectCompany.size() > 0 && selectCompany.get("audit").toString().equals("1")) {
			return new ReturnData(12, "企业用户无法推荐");
		}
		int selectUserParent = userDao.selectUserParent(user.getUser_id());
		if (selectUserParent > 0) {
			return new ReturnData(12, "只能推荐一次");
		}
		int flag = userDao.addUserGrade(user);
		if (flag > 0) {
			return new ReturnData(200, "推荐成功");
		}
		return new ReturnData(100, "推荐失败");
	}

	/***
	 * 根据手机号推荐
	 */
	@Override
	public ReturnData addUserMobile(User user) {
		if (StringTools.isEmpty(user.getMobile()) || StringTools.isEmpty(user.getUser_id())) {
			return new ReturnData(12, "参数有误");
		}
		String selectUsertEnter = userDao.selectUsertEnter(user.getUser_id());
		if (!StringTools.isEmpty(selectUsertEnter)) {
			return new ReturnData(12, "企业员工无法推荐");
		}
		Map<String, Object> selectUserMobile = userDao.selectUserMobile(user.getUser_id());
		if (selectUserMobile != null && selectUserMobile.get("mobile") != null
				&& selectUserMobile.get("mobile").equals(user.getMobile())) {
			return new ReturnData(12, "不能填写自己手机号");
		}
		String selectUserInfoId = userDao.selectUserInfoId(user.getMobile());
		if (StringTools.isEmpty(selectUserInfoId)) {
			return new ReturnData(12, "没有该用户");
		}
		user.setParent_id(selectUserInfoId);
		String selectUsertEnter2 = userDao.selectUsertEnter(selectUserInfoId);
		if (!StringTools.isEmpty(selectUsertEnter2)) {
			return new ReturnData(12, "企业员工无法推荐");
		}
		Map<String, Object> selectCompany = userDao.selectCompany(user.getParent_id());
		if (selectCompany != null && selectCompany.size() > 0 && selectCompany.get("audit").toString().equals("1")) {
			return new ReturnData(12, "企业用户无法推荐");
		}
		int selectUserParent = userDao.selectUserParent(user.getUser_id());
		if (selectUserParent > 0) {
			return new ReturnData(12, "只能推荐一次");
		}
		int flag = userDao.addUserGrade(user);
		Map<String, Object> map = userDao.selectUserMobile(user.getUser_id());
		flag = userDao.insertRecommendMobile(selectUserInfoId, map.get("mobile").toString());
		if (flag > 0) {
			return new ReturnData(200, "推荐成功");
		}
		return new ReturnData(100, "推荐失败");
	}

	/**
	 * 查询下级
	 * 
	 * @param userid
	 * @return
	 */
	@Override
	public ReturnData selectParentUser(User user) {
		if (StringTools.isEmpty(user.getParent_id())) {
			return new ReturnData(12, "参数有误");
		}
		List<Map<String, Object>> parentList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> mobile = userDao.selectParentUser(user);
		for (Map<String, Object> map : mobile) {
			User user2 = new User();
			user2.setParent_id(user.getParent_id());
			user2.setUser_id(map.get("user_id").toString());
			Double selectParentUserDetail = userDao.selectisTicheng(user2);
			if (selectParentUserDetail != null) {
				map.put("profit", selectParentUserDetail);
			} else {
				map.put("profit", 0);
			}
			User user1 = new User();
			user1.setParent_id(map.get("user_id").toString());
			user1.setIs_ent(user.getIs_ent());
			List<Map<String, Object>> selectParentUsertwo = userDao.selectParentUsertwo(user1);
			for (Map<String, Object> map2 : selectParentUsertwo) {
				User user3 = new User();
				user3.setParent_id(user.getParent_id());
				user3.setUser_id(map2.get("user_id").toString());
				Double selectParentUserDetail1 = userDao.selectisTicheng(user3);
				if (selectParentUserDetail1 != null) {
					map2.put("profit", selectParentUserDetail1);
				} else {
					map2.put("profit", 0);
				}
			}
			if (selectParentUsertwo != null && selectParentUsertwo.size() > 0) {
				userList.addAll(selectParentUsertwo);
			}

			map.put("subordinate", userList);
			userList = new ArrayList<Map<String, Object>>();
			;
		}
		parentList.addAll(mobile);

		if (parentList != null && parentList.size() > 0) {
			Collections.sort(parentList, new Comparator<Map<String, Object>>() {

				@Override
				public int compare(Map<String, Object> o1, Map<String, Object> o2) {
					// TODO Auto-generated method stub
					Date date1 = (Date) o1.get("create_time");
					Date date2 = (Date) o2.get("create_time");
					if (date1 != null) {
						return date1.getTime() > date2.getTime() ? -1 : 1;
					} else {
						return 1;
					}
				}

			});// 使用Collections的sort方法
			return new ReturnData(parentList, 200, "成功");
		}
		return new ReturnData(100, "暂无数据");
	}

	/**
	 * 查询下一级
	 * 
	 * @param userid
	 * @return
	 */
	@Override
	public ReturnData selectOneUser(User user) {
		if (StringTools.isEmpty(user.getParent_id())) {
			return new ReturnData(12, "参数有误");
		}
		List<Map<String, Object>> mobile = userDao.selectParentUser(user);

		if (mobile != null && mobile.size() > 0) {
			return new ReturnData(mobile, 200, "成功");
		}
		return new ReturnData(100, "暂无数据");
	}

	/**
	 * 查询下二级
	 * 
	 * @param userid
	 * @return
	 */
	@Override
	public ReturnData selectTwoUser(User user) {
		if (StringTools.isEmpty(user.getParent_id())) {
			return new ReturnData(12, "参数有误");
		}
		List<Map<String, Object>> parentList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> mobile = userDao.selectParentUser(user);
		for (Map<String, Object> map : mobile) {
			User user1 = new User();
			user1.setParent_id(map.get("user_id").toString());
			user1.setIs_ent(user.getIs_ent());
			List<Map<String, Object>> selectParentUsertwo = userDao.selectParentUsertwo(user1);
			parentList.addAll(selectParentUsertwo);
		}

		if (parentList != null && parentList.size() > 0) {
			Collections.sort(parentList, new Comparator<Map<String, Object>>() {

				@Override
				public int compare(Map<String, Object> o1, Map<String, Object> o2) {
					// TODO Auto-generated method stub
					Date date1 = (Date) o1.get("create_time");
					Date date2 = (Date) o2.get("create_time");
					if (date1 != null) {
						return date1.getTime() > date2.getTime() ? -1 : 1;
					} else {
						return 1;
					}
				}

			});// 使用Collections的sort方法
			return new ReturnData(parentList, 200, "成功");
		}
		return new ReturnData(100, "暂无数据");
	}

	/**
	 * 查询下级收益明细
	 * 
	 * @param userid
	 * @return
	 */
	@Override
	public ReturnData selectUserDetail(User user) {
		if (StringTools.isEmpty(user.getParent_id()) || StringTools.isEmpty(user.getDateSelect())
				|| StringTools.isEmpty(user.getIs_ban())) {
			return new ReturnData(12, "参数有误");
		}
		double selectTotal = 0.0;
		List<Map<String, Object>> parentList = new ArrayList<Map<String, Object>>();
		Map<String, Object> totalProfit = new HashMap<String, Object>();
		if (user.getIs_ban().equals("1")) {
			List<Map<String, Object>> mobile1 = userDao.selectParentUser(user);
			for (Map<String, Object> map : mobile1) {
				User user1 = new User();
				user1.setParent_id(user.getParent_id());
				user1.setDateSelect(user.getDateSelect());
				if (StringTools.isEmpty(user.getUser_id())) {
					user1.setUser_id(map.get("user_id").toString());
					List<Map<String, Object>> mobile = userDao.selectParentUserDetail(user1);
					List<Map<String, Object>> mobile3 = userDao.selectParentUserVipDetail(user1);
					parentList.addAll(mobile);
					parentList.addAll(mobile3);
				} else {
					user1.setUser_id(user.getUser_id());
					List<Map<String, Object>> mobile = userDao.selectParentUserDetail(user1);
					List<Map<String, Object>> mobile4 = userDao.selectParentUserVipDetail(user1);
					parentList.addAll(mobile);
					parentList.addAll(mobile4);
					break;
				}

			}

		} else {
			List<Map<String, Object>> mobile = userDao.selectParentUser(user);
			for (Map<String, Object> map : mobile) {
				User user1 = new User();
				user1.setParent_id(map.get("user_id").toString());
				List<Map<String, Object>> mobile2 = userDao.selectParentUser(user1);
				for (Map<String, Object> map2 : mobile2) {
					User user2 = new User();
					user2.setParent_id(user.getParent_id());
					user2.setDateSelect(user.getDateSelect());
					if (StringTools.isEmpty(user.getUser_id())) {
						user2.setUser_id(map2.get("user_id").toString());
						List<Map<String, Object>> selectParentUsertwo = userDao.selectParentUsertwoDetail(user2);
						List<Map<String, Object>> mobile5 = userDao.selectParentUserVipDetail(user2);
						parentList.addAll(selectParentUsertwo);
						parentList.addAll(mobile5);
					} else {
						user2.setUser_id(user.getUser_id());
						List<Map<String, Object>> selectParentUsertwo = userDao.selectParentUsertwoDetail(user2);
						List<Map<String, Object>> mobile5 = userDao.selectParentUserVipDetail(user2);
						parentList.addAll(selectParentUsertwo);
						parentList.addAll(mobile5);
						break;
					}

				}
			}
		}
		for (Map<String, Object> map : parentList) {
			if (map.get("profit") != null && !map.get("profit").toString().equals("")) {
				selectTotal += Double.parseDouble(map.get("profit").toString());
			}
		}
		DecimalFormat df = new DecimalFormat("######0.00");

		totalProfit.put("totalProfit", df.format(selectTotal));
		parentList.add(totalProfit);
		if (parentList != null && parentList.size() > 0) {
			Collections.sort(parentList, new Comparator<Map<String, Object>>() {

				@Override
				public int compare(Map<String, Object> o1, Map<String, Object> o2) {
					// TODO Auto-generated method stub
					Date date1 = (Date) o1.get("create_time");
					Date date2 = (Date) o2.get("create_time");
					if (date1 != null) {
						return date1.getTime() > date2.getTime() ? -1 : 1;
					} else {
						return 1;
					}
				}

			});// 使用Collections的sort方法

			return new ReturnData(parentList, 200, "成功");
		}

		return new ReturnData(100, "暂无数据");
	}

	/**
	 * 查询下级交易详情
	 */
	@Override
	public ReturnData selectdetail(User user) {
		if (StringTools.isEmpty(user.getUser_id()) || StringTools.isEmpty(user.getParent_id())) {
			return new ReturnData(12, "参数有误");
		}
		List<Map<String, Object>> selectdetail = userDao.selectdetail(user);
		if (selectdetail != null && selectdetail.size() > 0) {
			return new ReturnData(selectdetail, 200, "成功");
		}
		return new ReturnData(100, "暂无数据");
	}

	/**
	 * 查询企业交易提成
	 */
	@Override
	public ReturnData selectEnter(User user) {
		if (StringTools.isEmpty(user.getParent_id()) || StringTools.isEmpty(user.getDateSelect())) {
			return new ReturnData(12, "参数有误");
		}
		double selectTotal = 0.0;
		Map<String, Object> totalProfit = new HashMap<String, Object>();
		List<Map<String, Object>> selectdetail = userDao.selectEnterProfit(user);
		DecimalFormat df = new DecimalFormat("######0.00");
		for (Map<String, Object> map : selectdetail) {
			selectTotal += Double.parseDouble(map.get("profit").toString());
		}
		totalProfit.put("totalProfit", df.format(selectTotal));
		selectdetail.add(totalProfit);
		if (selectdetail != null && selectdetail.size() > 0) {
			return new ReturnData(selectdetail, 200, "成功");
		}
		return new ReturnData(100, "暂无数据");
	}

	@Override
	public ReturnData upgrade() {
		Map<String, Object> upgrade = userDao.upgrade();
		if (upgrade != null) {
			return new ReturnData(upgrade, 200, "成功");
		}
		return new ReturnData(100, "暂无数据");
	}

	@Override
	public ReturnData upgradeStop(String levelId) {
		int upgradeStop = userDao.upgradeStop(levelId);
		if(upgradeStop==1){
			return new ReturnData( 200, "成功");
		}
		
		return new ReturnData(100, "失败");
	}


}
